$(function () {
    var queryUrl = '../sparepartrequ/list';
    var Id = getQueryString('Id');
    if (Id) {
        queryUrl += '?Id=' + Id;
    }
    $("#jqGrid").Grid({
        url: queryUrl,
        colModel: [
            {label: '计划编码', name: 'planCode', index: 'PLAN_CODE', width: 80},
            {
                label: '计划类别', index: 'PLAN_TYPE', width: 80,
                formatter: function (value, col, row) {
                    return sysEnums.SPARE_NEEDS_PLAN_TYPE[row.planType];
                }
            },
            {label: '所属车间', name: 'workshopName', width: 80},
            {label: '编制单位/申请单位', name: 'deptName', index: 'APPLY_UNIT', width: 80},
            {label: '编制人', name: 'organName', index: 'ORGAN_USER', width: 80},
            {label: '编制月份', name: 'organMonth', index: 'ORGAN_MONTH', width: 80},
            {
                label: '是否已导出', name: 'isExported', index: 'IS_EXPORTED', width: 60,
                formatter: function (value, col, row) {
                    return sysEnums.SPARE_NEEDS_PLAN_EXPORT_STATUS[row.isExported];
                }
            },
            {
                label: '审批进度', name: 'devCode', width: 60, sortable: false,
                formatter: function (value, col, row) {
                    return "<button class='btn btn-outline btn-info' id='recordsText' onclick='vm.shviewOption(\"" + escape(JSON.stringify(row)) + "\")'>" + sysEnums.SPARE_NEEDS_PLAN_PROGRESS[row.progress] + "</button>";
                }
            },
            {
                label: '明细', width: 40, align: 'center', sortable: false,
                formatter: function (value, col, row) {
                    return "<button title='详细信息' class='btn btn-outline btn-info' onclick='vm.goPartDetail(\"" + row.planCode + "\", \"" + row.applyUnit + "\", \"" + row.id + "\", \"" + row.planType + "\")'><i class='fa fa-bars'></i></button>";
                }
            },
            /*{label: '审批状态', name: 'approvalStatus', index: 'APPROVAL_STATUS', width: 80},*/
            {name: 'id', key: true, hidden: true},
            {name: 'progress', hidden: true},
            {name: 'applyUnit', index: 'APPLY_UNIT', hidden: true}
        ]
    });
    // 加载备件需求计划审批人列表
    vm.loadApproverList();
});

var vm = new Vue({
    el: '#rrapp',
    data: {
        showList: true,
        title: null,
        sparePartRequ: {
            organMonth: '',
            planType: '', // 计划类别
            id: ''
        },
        uploadData: {},
        q: {
            organId: '', // 所属车间ID
            planCode: '',
            organName: '',
            planType: '',
            erpCode:'',
        },
        deptLoading: false,
        approverList: [], // 备件需求计划审批人员列表：包含车间主管、室主任、车间领导、制造处PE
        // 审核参数VO
        approveParam: {
            id: '', // 物件领料单ID
            zhuguanshenpiren: '', // 审批用户ID
            chejianjinglishenpiren: '', // 审批用户ID
            zhizaochupeshenpiren: '' // 审批用户ID
        },
        auditTableColumns: [
            {
                title: '环节名称',
                key: 'workitemName',
                width: 190
            },
            {
                title: '审批状态',
                key: 'state',
                width: 100,
                render: (h, params) => {
                    return sysEnums.OA_CHECK_FLAG[params.row.state];
                }
            },
            {
                title: '审批人',
                key: 'approverName',
                width: 100
            },
            {
                title: '审批时间',
                key: 'approveDate',
                width: 150
            },
            {
                title: '审批备注',
                key: 'remark',
                width: 150
            }
        ],
        auditTableData: [], // 审批table数据
        approveStatus: 1, // 审批状态
        approveRemark: '', // 审批备注
        planTypeList: enumsToListWithoutChange('SPARE_NEEDS_PLAN_TYPE'),
        workshopList: [] // 所属车间下拉option列表
    },
    created: function () {
        this.loadWorshopList();
    },
    methods: {
        cancel: function () {
            let _this = this;
            let id = getSelectedRow("#jqGrid");
            if (id == null) {
                return;
            }
            var data = getSelectedRowData("#jqGrid");
            if (data.progress == '5' || data.progress == '0') {
                iview.Message.error("备件需求计划未提交审核或已审批通过，无需取消！");
                return;
            }
            confirm('确定要取消备件需求计划[' + data.planCode + ']的审批申请?', function () {
                // 领料单编制完毕，提交审核
                Ajax.request({
                    url: "../sparepartrequ/cancel?id=" + id,
                    params: JSON.stringify(_this.approveParam),
                    type: "POST",
                    contentType: "application/json",
                    successCallback: function (r) {
                        alert('提交成功', function (index) {
                            vm.reload();
                        });
                    }
                });
            });
        },
        loadApproverList: function (id) {
            // 加载审批人员列表，一般为当前提交人所在部门的室主任
            Ajax.request({
                url: "../sys/user/spNeedsPlanApproverList",
                type: 'GET',
                async: true,
                successCallback: function (r) {
                    vm.approverList = r.approverList;
                }
            });
        },
        loadWorshopList: function () {
            var _this = this;
            Ajax.request({
                url: '../sys/dept/listByDeptLevel?deptLevel=2',
                async: true,
                successCallback: data => {
                    this.workshopList = data.list;
                }
            });
        },
        overview: function () {
            var contentUrl = '../spare/sparepartrequdetail.html?isQuery=1';
            // 获取需要概览的初稿拟定计划
            var planIds = getSelectedRows('#jqGrid');
            if (planIds) {
                contentUrl += '&planId=' + planIds
            }
            // 备件需求计划概览
            openWindow({
                type: 2,
                title: '<i class="fa fa-file-text-o"></i> 备件计划初稿拟定',
                content: contentUrl,
                btn: ['确定'],
                btn1: function (index) {
                    layer.close(index);
                }
            })
        },
        commit: function () {
            let _this = this;
            // 编制完毕后提交审核
            var planId = getSelectedRow("#jqGrid");
            if (!planId) {
                return;
            }
            var data = getSelectedRowData("#jqGrid");
            if (data.progress !== '0' && data.progress !== '4' && data.progress !== '6') {
                alert('当前需求计划审核中或已通过，无需重复提交!');
                return;
            }
            // 赋值
            this.approveParam = {
                id: planId, // 物件领料单ID
                zhuguanshenpiren: '', // 审批用户ID
                chejianjinglishenpiren: '', // 审批用户ID
                zhizaochupeshenpiren: '' // 审批用户ID
            }
            //任务指派后工单状态变为维修中
            openWindow({
                title: "请指定各流程节点审批人员",
                area: ['500px', '350px'],
                content: jQuery("#audit"),
                btn: ['确定', '取消'],
                btn1: function (index) {
                    // 领料单编制完毕，提交审核
                    Ajax.request({
                        url: "../sparepartrequ/commitApprove",
                        params: JSON.stringify(_this.approveParam),
                        type: "POST",
                        contentType: "application/json",
                        successCallback: function (r) {
                            layer.close(index);
                            alert('提交成功', function (index) {
                                vm.reload();
                            });
                        }
                    });
                }
            });
        },
        //审核详情
        shviewOption: function (res) {
            let data = JSON.parse(unescape(res))
            Ajax.request({
                url: '../sysoaprocess/queryAll',
                params: {busId: data.id, busType: 'SP_NEED'},
                type: 'POST',
                successCallback: function (res) {
                    vm.auditTableData = res.list;
                    layer.open({
                        type: 1,
                        title: "审核详情",
                        closeBtn: 0,
                        area: ['700px', '480px'],
                        offset: '10vh',
                        shadeClose: true,
                        skin: 'yourclass',
                        content: $('#auditHistoryArea')
                    });
                }
            });
        },
        updateCheck: function (url, params) {
            Ajax.request({
                url: url,
                params: params,
                contentType: "application/json",
                type: 'POST',
                successCallback: function (res) {
                    alert('审核成功!');
                    setTimeout(function () {
                        location.reload();
                    }, 1000);
                }
            });
        },
        goPartDetail: function (planCode, applyUnit, planId,planType) {
            openWindow({
                type: 2,
                area: ['100%', '100%'],
                title: '<i class="fa fa-bars"></i> 需求计划明细',
                content: '../spare/sparepartrequdetail.html?planCode=' + planCode + '&applyUnit=' + applyUnit + '&planId=' + planId+'&planType='+planType,
                cancel: function (index, layero) {
                    layer.close(index);
                    vm.reload();
                }
            })
        },
        query: function () {
            vm.reload();
        },
        add: function () {
            vm.showList = false;
            vm.title = "新增";
            vm.sparePartRequ = {
                organMonth: '',
                id: ''
            };
        },
        createNeedsPlan: function () {
            if (!vm.sparePartRequ.organMonth) {
                layer.alert('编制计划月份必选！', {icon: 5});
                return;
            } else {
                vm.sparePartRequ.organMonth = vm.GMTToStr(vm.sparePartRequ.organMonth);
            }
            if (!vm.sparePartRequ.planType) {
                layer.alert('计划类别必选！', {icon: 5});
                return;
            }
            /*
           校验下当前月份是否已编制过，如果已编制过需要给用户提示是否仍要继续
            */
            Ajax.request({
                url: '../sparepartrequ/checkOrganed',
                params: {
                    organMonth: vm.sparePartRequ.organMonth,
                    planType: vm.sparePartRequ.planType
                },
                type: "POST",
                successCallback: function (r) {
                    if (r.isExists == 1) {
                        confirm(vm.sparePartRequ.organMonth + '月份的车间需求计划已创建，是否仍要创建？', function () {
                            vm.saveOrUpdate();
                        });
                    } else {
                        vm.saveOrUpdate();
                    }
                }
            });
        },
        saveOrUpdate: function (event) {
            if (vm.sparePartRequ.organMonth) {
                vm.sparePartRequ.organMonth = vm.GMTToStr(vm.sparePartRequ.organMonth);
            }
            Ajax.request({
                url: "../sparepartrequ/save",
                params: JSON.stringify(vm.sparePartRequ),
                type: "POST",
                contentType: "application/json",
                successCallback: function (r) {
                    alert('操作成功', function (index) {
                        vm.reload();
                    });
                }
            });
        },
        del: function (event) {
            var ids = getSelectedRows("#jqGrid");
            if (ids == null) {
                return;
            }

            confirm('确定要删除选中的记录？', function () {
                Ajax.request({
                    url: "../sparepartrequ/delete",
                    params: JSON.stringify(ids),
                    type: "POST",
                    contentType: "application/json",
                    successCallback: function () {
                        alert('操作成功', function (index) {
                            vm.reload();
                        });
                    }
                });
            });
        },
        reload: function (event) {
            vm.showList = true;
            var page = $("#jqGrid").jqGrid('getGridParam', 'page');
            $("#jqGrid").jqGrid('setGridParam', {
                postData: vm.q,
                page: page
            }).trigger("reloadGrid");
        },
        reloadSearch: function () {
            vm.q = {
                organId: '',
                planCode: '',
                organName: '',
                planType: '',
                erpCode:''

            };
            vm.reload();
        },
        GMTToStr: function (time) {
            var date = new Date(time)
            var month = date.getMonth() + 1;
            if (month < 10) {
                month = '0' + month;
            }
            return date.getFullYear() + '-' + month;
        },
        //数据导出
        exportData: function () {
            var ids = getSelectedRows('#jqGrid');
            if (!ids) {
                return;
            }
            window.open('../sparepartrequ/export?planIds=' + ids);
        },
        test: function () {
            let needsPlanId = getSelectedRow('#jqGrid');
            if (!needsPlanId) {
                return;
            }
        }
    }
});
